package com.cloudcc.mobile.view.schedule;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.Bind;
import butterknife.OnClick;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.RequestListener;
import com.cloudcc.cloudframe.util.DateUtils;
import com.cloudcc.cloudframe.util.ListUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.ExtraConstant;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.ReceiverConstant;
import com.cloudcc.mobile.adapter.ScheduleListAdapter;
import com.cloudcc.mobile.adapter.ScheduleListAdapter.OnScheduleItemClickListener;
import com.cloudcc.mobile.entity.schedule.ScheduleEntity;
import com.cloudcc.mobile.event.ScheduleEventList.ScheduleListEvent;
import com.cloudcc.mobile.manager.CacheManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.presenter.SchedulePresenter;
import com.cloudcc.mobile.util.PopuWindowUtils;
import com.cloudcc.mobile.view.base.BaseFragment;
import com.cloudcc.mobile.view.web.CloudWebViewActivity;
import com.cloudcc.mobile.view.web.WebSyncDefaultProxy;
import com.cloudcc.mobile.view.web.WebSyncDefaultProxy.MonitorParam;
import com.cloudcc.mobile.weight.SwipeCalendarView;
import com.cloudcc.mobile.weight.SwipeCalendarView.OnCalendarChangeListener;
import com.cloudcc.mobile.weight.SwipeCalendarView.OnDayItemSelectListener;
import com.cloudcc.mobile.weight.SwipeCalendarView.OnLocationChangeListener;
import com.cloudcc.mobile.weight.SwipeCalendarView.Style;
import com.cloudcc.mobile.widget.CloudCCTitleBar;
import com.cloudcc.mobile.widget.CloudCCTitleBar.OnTitleBarClickListener;

/**
 * @Description: 这个页面有可能 是 查看别人的日历 有可能是 查看 自己的日历
 * @author wangzhiqiang
 * @date 2015-11-26 下午11:49:23
 * 
 */
public class ScheduleMainFragment extends BaseFragment implements IEventLife,
		OnDayItemSelectListener, OnScheduleItemClickListener,
		OnTitleBarClickListener {

	@Bind(R.id.listview)
	ListView mListView;

	@Bind(R.id.tv2)
	LinearLayout tv2;

	@Bind(R.id.schedule_date)
	TextView schedule_date;

	@Bind(R.id.no_schedule)
	LinearLayout no_schedule;

	@Bind(R.id.flipper)
	SwipeCalendarView mSwipeCalendarView;

	@Bind(R.id.headerbar)
	CloudCCTitleBar headerbar;

	@Bind(R.id.add_new)
	TextView add_new;

	private SchedulePresenter mSchedulePresenter = new SchedulePresenter();

	private List<ScheduleEntity> mScheduleListData;// 当前日历展示 月份的数据

	private String headerTilte = "我的日程";

	private ScheduleListAdapter scheduleAdapter;

	private String belongtoid;// 下属的id
	private List<Date> schedulesArrays;// 2015-01-10

	@Override
	public void init() {
		super.init();
		initHeader();
		register();
		initSwipe();
		requestDatafromCache();
		requestDataformNet();
		initReceiver();
	}

	private SyncReceiver mSyncReceiver;

	private void initReceiver() {
		mSyncReceiver = new SyncReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(ReceiverConstant.RECEIVE_REFRESH_SCHEDULE);
		mContext.registerReceiver(mSyncReceiver, filter);
	}

	private class SyncReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			requestDataformNet();
		}
	}

	/**
	 * 初始化 标题等 intent等
	 */
	private void initHeader() {
		Bundle bundle = getArguments();
		if (bundle != null) {
			belongtoid = bundle.getString(ExtraConstant.EXTRA_ID, "");
			headerTilte = bundle.getString(ExtraConstant.EXTRA_NAME, "日程列表");
		}
		schedule_date.setText(DateUtils.dateToString(new Date(), "yyyy年MM月"));
		headerbar.setTitle(headerTilte);
		headerbar.setOnTitleBarClickListener(this);
		if (!TextUtils.isEmpty(belongtoid)) {
			headerbar.getRightLayout().setVisibility(View.GONE);
			add_new.setVisibility(View.INVISIBLE);
			findViewById(R.id.no_schedule).setEnabled(false);
		}
	}

	/**
	 * 获取 日程成功的时候
	 * 
	 * @param event
	 */
	public void onEventMainThread(ScheduleListEvent event) {
		headerbar.completeProgress();
		if (event.isError()) {
			return;
		}
		mScheduleListData = event.getData();
		// 当前选择的跟 当前手机上面的日期是同一个月的话 就缓存
		if (com.cloudcc.mobile.util.DateUtils.isSameMonth(
				mSwipeCalendarView.getmSelectDate(), new Date())) {
			CacheManager.getInstance().cacheThisMonthSchedule(
					CacheManager.IKey.SCHEDULE_MONTH, mScheduleListData);
		}
		refreshScheduleDataOneDay(mSwipeCalendarView.getmSelectDate());
		refreshCalendarAdapter();
	}

	/**
	 * 根据日期 从 当前 月份日程数据中获取当前天的日程列表
	 * 
	 * @return
	 */
	private List<ScheduleEntity> getschedulesByDay(Date date) {
		/**
		 * 逻辑 任务 截至日期 大于等于 当前选择日期 日程 开始日期跟结束日期 之间 包括 当前选择日期的
		 * */
		List<ScheduleEntity> schedules = new ArrayList<ScheduleEntity>();
		if (ListUtils.isEmpty(mScheduleListData)) {
			return schedules;
		}
		for (ScheduleEntity schedule : mScheduleListData) {
			if (shoudScheduleInDay(date, schedule)) {
				schedules.add(schedule);
			}
		}
		Collections.sort(schedules);
		return schedules;
	}

	/**
	 * 判断一个 日程任务对象 是不是 在 指定的某一天中
	 * 
	 * @param date
	 *            日期
	 * @param schedule
	 *            任务 日程对象
	 * @return
	 */
	private boolean shoudScheduleInDay(Date date, ScheduleEntity schedule) {
		final Calendar cal1 = Calendar.getInstance();
		cal1.setTime(date);
		if (schedule.isTask()) {// 任务
			Date sdate = schedule.getExpiredateForDate();
			if (sdate != null) {
				final Calendar cals = Calendar.getInstance();
				cals.setTime(sdate);
				return com.cloudcc.mobile.util.DateUtils.isSameDay(cal1, cals);
			}
		} else {// 日程
			Date bdate = schedule.getBegintimeForDate();
			Date edate = schedule.getEndtimeForDate();
			if (bdate == null || edate == null) {
				return false;
			}
			final Calendar calb = Calendar.getInstance();
			calb.setTime(bdate);
			final Calendar cale = Calendar.getInstance();
			cale.setTime(edate);
			if (com.cloudcc.mobile.util.DateUtils.isSameDay(cal1, calb)// 开始时间是跟今天一天
					|| com.cloudcc.mobile.util.DateUtils.isSameDay(cal1, cale)// 结束时间跟今天一天
					|| (calb.before(cal1) && cale.after(cal1)))// 在今天之前开始
																// 在今天之后结束
			{
				return true;
			}

		}
		return false;
	}

	/**
	 * 刷新日历 显示当天的日程等
	 */
	private void refreshScheduleDataOneDay(Date date) {
		// 刷新当天的
		if (scheduleAdapter == null) {
			scheduleAdapter = new ScheduleListAdapter(mContext);
			scheduleAdapter.setOnScheduleItemClickListener(this);
			mListView.setAdapter(scheduleAdapter);
		}
		// 获得当天的数据
		List<ScheduleEntity> list = getschedulesByDay(date);
		no_schedule.setVisibility(ListUtils.isEmpty(list) ? View.VISIBLE
				: View.GONE);
		mListView.setVisibility(ListUtils.isEmpty(list) ? View.GONE
				: View.VISIBLE);
		scheduleAdapter.changeData(list);
		scheduleAdapter.refreshTimeLine();
	}

	@Override
	public void onResume() {
		super.onResume();
		if (scheduleAdapter != null) {
			scheduleAdapter.refreshTimeLine();
		}
	}

	private void initSwipe() {
		mSwipeCalendarView
				.setOnLocationChangeListener(new OnLocationChangeListener() {
					@Override
					public void onPrevious(Date date) {
						// 刷新任务列表
						if (isThisDayInNowDataMonth(date)) {
							requestDataformNet();
						} else {
							mSwipeCalendarView.mAdapter.notifyDataSetChanged();
						}
					}

					@Override
					public void onNext(Date date) {
						if (isThisDayInNowDataMonth(date)) {
							requestDataformNet();
						} else {
							mSwipeCalendarView.mAdapter.notifyDataSetChanged();
						}
					}

					@Override
					public void onStyleChange(Style style) {
					}
				});
		mSwipeCalendarView
				.setOnCalendarChangeListener(new OnCalendarChangeListener() {
					@Override
					public View getView(int position, View convertView,
							Date date) {
						if (convertView == null) {
							convertView = LayoutInflater.from(mContext)
									.inflate(R.layout.calendar_item, null);
						}
						// 点击事件
						// 判断 当前日期是不是本月的
						TextView textView = (TextView) convertView
								.findViewById(R.id.tv1);
						boolean sameMonth = com.cloudcc.mobile.util.DateUtils
								.isSameMonth(date,
										mSwipeCalendarView.getmCurrentUIDate());
						textView.setTextColor(sameMonth ? Color.BLACK
								: Color.GRAY);
						// 小点
						TextView ivDot = (TextView) convertView
								.findViewById(R.id.iv2);
						boolean hasTaskInToday = hasTaskOrScheduleInDay(date);
						ivDot.setVisibility(hasTaskInToday ? View.VISIBLE
								: View.GONE);
						ImageView ivBackground = (ImageView) convertView
								.findViewById(R.id.iv1);
						SimpleDateFormat dateFormat = new SimpleDateFormat("dd");
						textView.setText(dateFormat.format(date));
						if (date.equals(mSwipeCalendarView.getmSelectDate())) {
							ivBackground.setImageResource(R.drawable.circle);
							textView.setTextColor(Color.WHITE);
						} else {
							ivBackground.setImageDrawable(null);
						}
						return convertView;
					}

					@Override
					public void onNotifyDataChanged() {
					}
				});
		mSwipeCalendarView.setOnDayItemSelectListener(this);
	}

	/**
	 * 判断 当前日期是不是有 任务
	 * 
	 * @param date
	 * @return
	 */
	private boolean hasTaskOrScheduleInDay(Date date) {
		if (schedulesArrays == null) {
			return false;
		}
		for (Date d : schedulesArrays) {
			if (com.cloudcc.mobile.util.DateUtils.isSameDay(d, date)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void OnItemSelected(int pos, Date date) {
		// 刷新任务 日程列表 换算到 当前选择时间的
		refreshScheduleDataOneDay(date);
	}

	@OnClick(R.id.schedule_today)
	public void clickToday() {
		mSwipeCalendarView.SelectData(new Date());
		mSwipeCalendarView.showWeekUI(mSwipeCalendarView.getmSelectDate());
		refreshScheduleDataOneDay(mSwipeCalendarView.getmSelectDate());
	}

	@OnClick(R.id.schedule_look_other)
	public void clickLookOther() {
		Intent intent = new Intent(mContext, SubStaffListActivity.class);
		startActivity(intent);
		getActivity().finish();
	}

	private PopupWindow mRightMenu;

	private class MyMenuClick implements OnClickListener {

		private String url = "";

		public MyMenuClick(String url) {
			super();
			this.url = url;
		}

		@Override
		public void onClick(View v) {
			PopuWindowUtils.dissmiss(mRightMenu);
			MonitorParam monitorParam = new MonitorParam(
					new String[] { "m=save" }, WebSyncDefaultProxy.STEP_START,
					new String[] { "m=query" }, true,
					WebSyncDefaultProxy.STEP_OVERRIDEURL);
			Intent intent = new Intent(mContext, CloudWebViewActivity.class);
			intent.putExtra(
					"callback",
					WebSyncDefaultProxy
							.creatDefaultProxy(
									ReceiverConstant.RECEIVE_REFRESH_SCHEDULE)
							.addMonitorParam(monitorParam).addHomeMonitor());
			intent.putExtra(ExtraConstant.EXTRA_URL, url);
			startActivity(intent);
		}
	};

	/**
	 * 根据 text提示 判断 是不是 切换月份 需要请求服务器了
	 * 
	 * @param date
	 * @return 如果 true 需要请求 如果false 就不用请求服务器
	 */
	private boolean isThisDayInNowDataMonth(Date date) {
		// Date schedule_date.setText(DateUtils.dateToString(date,"yyyy年MM月"));
		// 上一个月份
		String lastMonth = schedule_date.getText().toString().trim();
		// 上一个月
		String lastMonthNum = StringUtils.substring(lastMonth, 5, 7);
		// 当前选择的ui月份
		String nowUIMonth = DateUtils.dateToString(date, "yyyy年MM月");
		String monthNum = StringUtils.substring(nowUIMonth, 5, 7);
		schedule_date.setText(nowUIMonth);
		return !StringUtils.equals(lastMonthNum, monthNum);
	}

	@Override
	public void OnItemClickHeader(int pos, ScheduleEntity t) {
		// 显示 dialog
		createWainting();
		final String iid = t.id;
		mSchedulePresenter.completeTask(t.id, new RequestListener() {

			@Override
			public void onSuccess(Object arg0) {
				dismissWainting();
				refreshCompleteData(iid);
			}

			@Override
			public void onFailure(ErrorInfo arg0) {
				dismissWainting();
				// 关闭
				Toast.makeText(mContext, arg0.getErrorMessage(), 0).show();
			}
		});
	}

	@Override
	public void onItemScheduleClick(int pos, ScheduleEntity t) {
		Intent intent = new Intent(mContext, CloudWebViewActivity.class);
		intent.putExtra(ExtraConstant.EXTRA_URL, UrlManager.getManager()
				.getTaskOrScheduleDetailUrl(t.id));
		MonitorParam monitorParam = new MonitorParam(
				new String[] { "m=delete" }, WebSyncDefaultProxy.STEP_START,
				new String[] { "taskcondition=today", "m=list&objid=task",
						"eventcondition=today" }, true,
				WebSyncDefaultProxy.STEP_START);
		MonitorParam monitorParam2 = new MonitorParam(
				new String[] { "m=save" }, WebSyncDefaultProxy.STEP_START,
				new String[] { "m=query" }, true,
				WebSyncDefaultProxy.STEP_OVERRIDEURL);
		MonitorParam monitorParam3 = new MonitorParam(new String[] {
				"taskcondition=today", "eventcondition=today" },
				WebSyncDefaultProxy.STEP_START, new String[] {
						"taskcondition=today", "eventcondition=today" }, true,
				WebSyncDefaultProxy.STEP_START);
		monitorParam3.isCallBack = false;
		intent.putExtra(
				"callback",
				WebSyncDefaultProxy
						.creatDefaultProxy(
								ReceiverConstant.RECEIVE_REFRESH_SCHEDULE)
						.addMonitorParam(monitorParam)
						.addMonitorParam(monitorParam2)
						.addMonitorParam(monitorParam3).addHomeMonitor());

		startActivity(intent);
	}

	/**
	 * 刷新完成任务
	 * 
	 * @param id
	 */
	private void refreshCompleteData(String id) {
		removefromScheduleList(id);
		refreshScheduleDataOneDay(mSwipeCalendarView.getmSelectDate());
	}

	/**
	 * 从全部的任务中删除一个 任务 根据id
	 * 
	 * @param id
	 */
	private void removefromScheduleList(String id) {
		if (ListUtils.isEmpty(mScheduleListData)) {
			return;
		}
		int pos = -1;
		for (int i = 0; i < mScheduleListData.size(); i++) {
			ScheduleEntity item = mScheduleListData.get(i);
			if (StringUtils.equalsIgnoreCase(item.id, id)) {
				pos = i;
				break;
			}
		}
		if (pos != -1) {
			mScheduleListData.remove(pos);
		}
	}

	private void refreshCalendarAdapter() {
		refreshTaskUI();
		if (mSwipeCalendarView.mAdapter != null) {
			mSwipeCalendarView.mAdapter.notifyDataSetChanged();
		}

	}

	private void refreshTaskUI() {
		schedulesArrays = new ArrayList<Date>();
		schedulesArrays.clear();

		// 当前月份的所有任务
		if (ListUtils.isEmpty(mScheduleListData)) {
			return;
		}
		// 日历当前展示月份的数据
		Date[] dateOfMonth = DateUtils.getDateOfMonth(mSwipeCalendarView
				.getmCurrentUIDate());
		for (int i = 0; i < dateOfMonth.length; i++) {
			if (!ListUtils.isEmpty(getschedulesByDay(dateOfMonth[i]))) {
				schedulesArrays.add(dateOfMonth[i]);
			}
		}
	}

	/**
	 * 从缓存中获取 当月数据
	 */
	private void requestDatafromCache() {
		mScheduleListData = CacheManager.getInstance()
				.getThisMonthScheduleByCache(CacheManager.IKey.SCHEDULE_MONTH);
		refreshScheduleDataOneDay(mSwipeCalendarView.getmSelectDate());
		refreshCalendarAdapter();
	}

	/**
	 * 请求网络数据
	 */
	private void requestDataformNet() {
		headerbar.beginProgress();
		mSchedulePresenter.getScheduleList(belongtoid,
				mSwipeCalendarView.getmCurrentUIDate());
	}

	@Override
	public int getLayoutId() {
		return R.layout.schedule_main;
	}

	@Override
	public void register() {
		EventEngine.register(this);
	}

	@Override
	public void onDestroy() {
		unRegister();
		super.onDestroy();
	}

	@Override
	public void unRegister() {
		EventEngine.uregister(this);
	}

	@Override
	public void onClickLeft(View v) {
		getActivity().finish();
	}

	@Override
	public void onClickRight(View v) {
		showRightNew();
	}

	@OnClick(R.id.no_schedule)
	public void clickNew() {
		showRightNew();
	}

	private void showRightNew() {
		PopuWindowUtils.dissmiss(mRightMenu);
		View contentView = (View) View.inflate(mContext,
				R.layout.popu_schedule_new, null);
		LinearLayout subContainer = (LinearLayout) contentView
				.findViewById(R.id.pop_holder);
		for (int i = 0; i < 2; i++) {
			View containerView = View.inflate(mContext,
					R.layout.layout_pop_item, null);
			ImageView ivLogo = (ImageView) containerView
					.findViewById(R.id.pop_item_image);
			ivLogo.setVisibility(View.VISIBLE);
			TextView tvTitle = (TextView) containerView
					.findViewById(R.id.pop_item_text);
			ImageView LIne = (ImageView) containerView
					.findViewById(R.id.item_line);
			if (i == 0) {
				ivLogo.setImageResource(R.drawable.ico_schedule);
				containerView.setOnClickListener(new MyMenuClick(UrlManager
						.getManager().addReturnUrl(
								UrlManager.getManager().getNewTaskOrSchedule(
										false))));
				tvTitle.setText("新建日程");
			} else {
				containerView.setOnClickListener(new MyMenuClick(UrlManager
						.getManager().addReturnUrl(
								UrlManager.getManager().getNewTaskOrSchedule(
										true))));
				ivLogo.setImageResource(R.drawable.ico_task);
				tvTitle.setText("新建任务");
				LIne.setVisibility(View.INVISIBLE);
			}
			subContainer.addView(containerView);
		}
		mRightMenu = new PopupWindow(contentView,
				ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		mRightMenu.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
		mRightMenu.setFocusable(true);
		mRightMenu.showAsDropDown(headerbar.getRightLayout());
	}

}
